import { postAction, spliceUrl } from '../../common/js/api/vue3-axios-utils.js'
export const mixin = {
	data() {
		return {
			from: '',
			pathname: '',
		}
	},
	created() {
		if (this.isVxin) {
			// add by sun
			this.from = url('?from')
			const code = url('?code')
			if (code) {
				// 授权完成，通过code换取用户id，跳转页面
				this.handleGetUserInfoByWechatCode(code)
			} else {
				const url = encodeURIComponent(this.initCallbackUrl())
				window.location.href = this.createAuthUrl(url)
			}
		}
	},
	computed: {
		isVxin() {
			//除了企业微信的都进行授权
			let ua = navigator.userAgent.toLowerCase()
			console.log(navigator.userAgent.toLowerCase())
			if (ua.match(/MicroMessenger/i) && ua.match(/wxwork/i)) {
				return false
			} else {
				return true
			}
		},
	},
	methods: {
		handleGetUserInfoByWechatCode(code) {
			postAction(spliceUrl('/sys/wechat/oa/patient/login'), {
				identity: 1,
				jsCode: code,
			}).then(res => {
				res = res.data
				if (res.success) {
					localStorage.setItem('pid', res.result.userId)
					this.fetchData()
				} else {
					vant.Toast.fail(res.message)
				}
			})
		},
		initCallbackUrl() {
			const protocol = document.location.protocol + '//'
			let host = window.location.host
			console.log(host)
			const pathname = window.location.pathname
			if (host.indexOf('test') != -1) {
				host = 'h5.test.dtx-tech.com'
			}
			this.pathname = pathname
			return protocol + host + pathname
		},
		createAuthUrl(url) {
			console.log(url)
			let state = ''
			if (this.from == 'roleIndex') {
				state = 'roleIndex'
			}
			return (
				'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx856bd338d5ffb469&redirect_uri=' +
				url +
				'&response_type=code&scope=snsapi_userinfo&state=' +
				state +
				'#wechat_redirect'
			)
		},
	},
}
